import React, { lazy, Suspense } from 'react'
import { Navigate, useRoutes } from 'react-router-dom'

const Login = lazy(() => import('../pages/Login/index'))
const NotFound = lazy(() => import('../pages/NotFound/index'))

export interface MetaProps {
  keepAlive?: boolean // 切换路由是否缓存组件
  requiresAuth?: boolean
  title: string
  key?: string
}
export interface RouterArr {
  path?: string
  element?: React.ReactNode
  meta?: MetaProps
  isLink?: boolean
  children?: RouterArr[]
}

// vite Glob 自动引入指定目录下所有模块  https://cn.vitejs.dev/guide/features.html#glob-import
const routerModules: any = import.meta.glob('./modules/*.tsx', {
  eager: true,
  import: 'default'
})

export const routerArray: RouterArr[] = []
// 方法一
// for (const path in routerModules) {
//   routerArray.push(...routerModules[path])
// }
// 方法二
Object.keys(routerModules).forEach(path => {
  routerArray.push(...routerModules[path])
})

export const allRoutes: RouterArr[] = [
  {
    path: '/',
    element: <Navigate to={'/login'} />
  },
  {
    path: '/login',
    element: <Login />,
    meta: {
      requiresAuth: false,
      title: '登录',
      key: 'login'
    }
  },
  ...routerArray,
  {
    path: '*',
    element: <NotFound />
  }
]

const Router = () => {
  const router = useRoutes(allRoutes)
  return router
}
export default Router
